<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 左侧个人信息展示 -->
      <el-col :span="6">
        <el-card class="profile-card">
          <div class="profile-header">
            <div class="avatar-container">
              <el-avatar :size="100" :src="userInfo.avatar ? userAvatarUrl : ''" />
              <div class="avatar-upload">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-change="handleAvatarChange"
                  accept="image/*"
                >
                  <el-button size="small" type="primary">更换头像</el-button>
                </el-upload>
              </div>
            </div>
            <h2>{{ userInfo.nikeName }}</h2>
            <p>{{ userInfo.role === 'ADMIN' ? '管理员' : '普通用户' }}</p>
          </div>
          <div class="profile-info">
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span>用户名：{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <el-icon><Message /></el-icon>
              <span>邮箱：{{ userInfo.email }}</span>
            </div>
            <div class="info-item">
              <el-icon><Phone /></el-icon>
              <span>手机号：{{ userInfo.phone }}</span>
            </div>
            <div class="info-item">
              <el-icon><Calendar /></el-icon>
              <span>创建账号时间：{{ formatDate(userInfo.createTime) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧编辑区域 -->
      <el-col :span="18">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-tabs v-model="activeTab">
                <el-tab-pane label="基本资料" name="basic"></el-tab-pane>
                <el-tab-pane label="修改密码" name="password"></el-tab-pane>
              </el-tabs>
            </div>
          </template>
          
          <!-- 基本资料表单 -->
          <div v-if="activeTab === 'basic'">
            <el-form
              ref="editFormRef"
              :model="editForm"
              :rules="editRules"
              label-width="100px"
              label-position="right"
            >
              <el-form-item label="用户昵称" prop="nikeName" required>
                <el-input v-model="editForm.nikeName" placeholder="请输入昵称" />
              </el-form-item>
              <el-form-item label="手机号码" prop="phone" required>
                <el-input v-model="editForm.phone" placeholder="请输入手机号" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email" required>
                <el-input v-model="editForm.email" placeholder="请输入邮箱" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitEdit">保存</el-button>
                <el-button @click="resetForm">关闭</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 修改密码表单 -->
          <div v-if="activeTab === 'password'">
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="100px"
            >
              <el-form-item label="原密码" prop="oldPassword">
                <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码" show-password />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitPasswordChange">保存</el-button>
                <el-button @click="resetPasswordForm">关闭</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Message, Phone, Calendar, Money } from '@element-plus/icons-vue'
import { getCurrentUser, updateUser, changePassword } from '@/api/user'
import { post } from '@/utils/request'

// 当前激活的标签页
const activeTab = ref('basic')

// 用户信息
const userInfo = ref({})

// 头像URL
const userAvatarUrl = computed(() => {
  return userInfo.value.avatar || ''
})

// 头像上传相关
const avatarFile = ref(null)

// 处理头像上传
const handleAvatarChange = (file) => {
  avatarFile.value = file.raw
  if (file) {
    uploadAvatar()
  }
}

// 上传头像到服务器
const uploadAvatar = async () => {
  if (!avatarFile.value) {
    ElMessage.warning('请选择头像图片')
    return
  }
  
  const formData = new FormData()
  formData.append('file', avatarFile.value)
  
  try {
    ElMessage.info('头像上传中...')
    const res = await post('/file/upload', formData)
    if (res.success) {
      // 更新用户头像
      const updateRes = await updateUser({
        id: userInfo.value.id,
        avatar: res.data
      })
      
      if (updateRes.success) {
        ElMessage.success('头像更新成功')
        // 重新获取用户信息
        fetchUserInfo()
      } else {
        ElMessage.error(updateRes.msg || '头像信息保存失败')
      }
    } else {
      ElMessage.error(res.msg || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败：', error)
    ElMessage.error('头像上传失败，请检查网络连接')
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getCurrentUser()
    if (res.success) {
      userInfo.value = res.data
      // 初始化编辑表单
      Object.assign(editForm, {
        nikeName: res.data.nikeName || '',
        email: res.data.email || '',
        phone: res.data.phone || '',
        sex: res.data.sex || '男'
      })
    } else if (!res._showError) {
      ElMessage.error(res.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败：', error)
    if (!error._showError) {
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '获取用户信息失败')
      } else {
        ElMessage.error('获取用户信息失败，请检查网络连接')
      }
    }
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 编辑信息
const editFormRef = ref(null)
const editForm = reactive({
  nikeName: '',
  email: '',
  phone: '',
  sex: '男'
})

const editRules = {
  nikeName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const submitEdit = async () => {
  if (!editFormRef.value) return
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await updateUser({
          id: userInfo.value.id,
          ...editForm
        })
        if (res.success) {
          ElMessage.success('更新成功')
          fetchUserInfo()
        } else if (!res._showError) {
          // 显示后端返回的错误信息
          ElMessage.error(res.msg || '更新用户信息失败')
        }
      } catch (error) {
        console.error('更新用户信息失败：', error)
        // 如果有响应数据，则显示后端返回的错误信息
        if (!error._showError) {
          if (error.response && error.response.data) {
            ElMessage.error(error.response.data.msg || '更新用户信息失败')
          } else {
            ElMessage.error('更新用户信息失败，请检查网络连接')
          }
        }
      }
    }
  })
}

const resetForm = () => {
  editFormRef.value?.resetFields()
  // 重新设置表单数据为当前用户数据
  Object.assign(editForm, {
    nikeName: userInfo.value.nikeName || '',
    email: userInfo.value.email || '',
    phone: userInfo.value.phone || '',
    sex: userInfo.value.sex || '男'
  })
}

// 修改密码
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
}

const submitPasswordChange = async () => {
  if (!passwordFormRef.value) return
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await changePassword({
          id: userInfo.value.id,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        if (res.success) {
          ElMessage.success('密码修改成功')
          resetPasswordForm()
        } else if (!res._showError) {
          // 显示后端返回的错误信息
          ElMessage.error(res.msg || '修改密码失败')
        }
      } catch (error) {
        console.error('修改密码失败：', error)
        // 如果有响应数据，则显示后端返回的错误信息
        if (!error._showError) {
          if (error.response && error.response.data) {
            ElMessage.error(error.response.data.msg || '修改密码失败')
          } else {
            ElMessage.error('修改密码失败，请检查网络连接')
          }
        }
      }
    }
  })
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  margin-bottom: 20px;
}

.profile-header {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 10px;
}

.avatar-upload {
  margin-top: 10px;
}

.avatar-uploader :deep(.el-upload) {
  display: block;
  text-align: center;
}

.profile-header h2 {
  margin: 10px 0;
  font-size: 20px;
}

.profile-header p {
  color: #666;
  margin: 0;
}

.profile-info {
  margin: 20px 0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.info-item .el-icon {
  margin-right: 10px;
  font-size: 18px;
  color: #409EFF;
}

.card-header {
  padding: 0;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}
</style> 